﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace UpdataStart
{
    public partial class UpdateForm : Form
    {
        string tempPath;
		ReleaseList localRelease;
		ReleaseList remoteRelease;
        ReleaseFile[] diff;

        bool downloaded;

        int totalSize;

        const string RetryText = " 重  试 ";
        const string FinishText = " 完 成 ";

        public UpdateForm()
        {
            InitializeComponent();
        }

        public UpdateForm(
			string tempPath,
			ReleaseList localRelease,
			ReleaseList remoteRelease
			)
		{
			InitializeComponent();
			this.tempPath = tempPath;
			this.localRelease = localRelease;
			this.remoteRelease = remoteRelease;
			
		}

        private void UpdateForm_Load(object sender, EventArgs e)
        {
          Init();
        }

        private void Init()
        {
            label2.Text = "下载进度";
            label1.Text = string.Format("当前版本：{0} 最新版本：{1} 发布时间：{2}", localRelease.MinVersion, remoteRelease.MinVersion,
                remoteRelease.ReleaseDate);
            //升级内容
            textBox1.Text = remoteRelease.UpdateDescription;

            diff = localRelease.GetDifferences(remoteRelease, out totalSize);
            if (diff == null)
            {
                button1.Text = "升级完成!";
                return;
            }
            progressBar1.Maximum = totalSize * 1024;
            progressBar1.Step = 10;

         //   Upgrade();

        }

        Thread trd;
        private void Upgrade()
        {
            trd = new Thread(new ThreadStart(DoUpgrade));
            trd.IsBackground = true;
            trd.Start();
        }

        private void DoUpgrade()
        {
            downloaded = false;
            progressBar1.Value = 0;
            foreach (ReleaseFile file in diff)
            {
                try
                { 
                    DownloadTool.DownloadFile(tempPath,  remoteRelease.ReleaseUrl +remoteRelease.ReleaseVersion, file.FileName, progressBar1, label2);
                }
                catch (Exception ex)
                {
                    AppTool.DeleteTempFolder(tempPath);
                    MessageBox.Show(file.FileName + "下载失败，请稍后再试");
                    OptionalUpdate = true;
                    trd.Abort();
                    return;
                }             
            }
            try
            {
                foreach (ReleaseFile file in diff)
                {
                    string dir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory + file.FileName);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    //将从服务器下载的文件Copy到指定目录
                    string[] paths = AppDomain.CurrentDomain.BaseDirectory.Split('\\');//拆分成数组        
                    string result = "";
                    for (int i = 0; i < paths.Length - 2; i++)
                    {
                        result += paths[i]+"\\";
                    }  
                    File.Copy(tempPath + file.FileName,result+file.Directory+"\\"+ file.FileName, true);      
                }
            }
            catch (Exception ex)
            {
                AppTool.DeleteTempFolder(tempPath);
                MessageBox.Show(ex.Message, "更新失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                OptionalUpdate = true;
                trd.Abort();
                return;
            }
            remoteRelease.Save(localRelease.FileName);
            downloaded = true;
            CreateShortcut();
            Application.Exit();
            //AppTool.Start(localRelease.ApplicationStart);
            //AppTool.Start("suny.exe");
            MessageBox.Show("程序升级完毕，请重新启动!", "系统提示", MessageBoxButtons.OK);
            trd.Abort();
        }

        private bool OptionalUpdate
        {
            set
            {
                ;
            }
        }

        private void CreateShortcut()
        {
            string fileName = remoteRelease.AppName;
            foreach (char invalidChar in Path.GetInvalidFileNameChars())
            {
                fileName = fileName.Replace(invalidChar, '_');
            }
            string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) +
                "\\" + fileName + ".lnk";
            if (File.Exists(path))
                return;

        }

        //删除原来xml
        private void UpdateForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            AppTool.DeleteTempFolder(tempPath);
        }


        //推出
        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
          //  AppTool.Start(localRelease.ApplicationStart); 
        }

        //升级
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            Upgrade();
        }
    }
}
